package com.example.shop.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shop.common.api.ServiceReturn;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.logistics.dto.DeliveryBill;
import com.example.shop.logistics.service.LogisticsService;
import com.example.shop.mapper.CourierMapper;
import com.example.shop.mapper.OrderMapper;
import com.example.shop.order.enums.OrderState;
import com.example.shop.pojo.Courier;
import com.example.shop.pojo.Merchant;
import com.example.shop.pojo.Order;
import com.example.shop.pojo.User;
import com.example.shop.rabbitmq.component.OrderComponents;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LogisticsServiceImpl implements LogisticsService {

    private final OrderMapper orderMapper;
    private final CourierMapper courierMapper;
    private final RabbitTemplate rabbitTemplate;

    public LogisticsServiceImpl(OrderMapper orderMapper, CourierMapper courierMapper, RabbitTemplate rabbitTemplate) {
        this.orderMapper = orderMapper;
        this.courierMapper = courierMapper;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Transactional
    @Override
    public ServiceReturn<Boolean> deliveryGoods(Merchant deliveryMerchant, DeliveryBill bill) {
        Order order = orderMapper.selectById(bill.getOrderId());
        if(order==null){
            return new ServiceReturn<>(ServiceStateCode.NOT_EXIST_ORDER,false);
        }
        Courier courier = bill.toCourier(deliveryMerchant);
        courier.setCourierId(order.getCourierId());
        //更新物流单的发货者
        courierMapper.updateNotNull(courier);
        //更新订单为待收货状态
        orderMapper.updateFieldById("order_state", OrderState.DUE_IN_GOODS.getOrderState(), order.getOrderId());
        return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
    }

    @Override
    public ServiceReturn<Boolean> ConfirmGoods(User user, long orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId())
                .eq("order_id",orderId)
                .eq("order_state",OrderState.DUE_IN_GOODS.getOrderState());
        Order order = orderMapper.selectOne(queryWrapper);
        if(order==null){
            return new ServiceReturn<>(ServiceStateCode.NOT_EXIST_ORDER,false);
        }
        //查询该物流是否被签收

        //更新订单为待收货状态
        orderMapper.updateFieldById("order_state", OrderState.STAY_EVALUATE, order.getOrderId());
        //发送一个自动评价消息，15天内没有对其评论，则会自动评论
        rabbitTemplate.convertAndSend(OrderComponents.ORDER_EXCHANGE,OrderComponents.EVALUATE_ROUTING_KEY,order);
        return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
    }
}
